<template>
  <el-dialog title="素材命名" :visible.sync="visible" width="30%" :before-close="handleClose" :close-on-click-modal="false" :inline="true">
    <el-form label-position="left" label-width="80px" :model="attach" size="small">
      <el-form-item label="素材名称">
        <el-input v-model="attach.filename" type="text" show-word-limit maxlength="100">
          <template slot="append">
            {{ attach.append }}
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      require: true,
      default: _ => {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      attach: {
        filename: '',
        append: ''
      }
    };
  },
  created() {
    const index = this.item.filename.lastIndexOf('.'); // 取到文件名开始到最后一个点的长度
    const fileFormat = this.item.filename.substring(index + 1);
    const fileName = this.item.filename.substring(0, index);
    this.$set(this.attach, 'filename', fileName);
    this.$set(this.attach, 'append', '.' + fileFormat);
  },
  methods: {
    handleClose: function() {
      this.$emit('update:visible', false);
    },
    onSubmit: function() {
      if (!this.attach.filename) {
        this.$message.warning('请填写素材名称');
        return false;
      }
      const data = {
        filename: this.attach.filename + this.attach.append
      };
      this.$http.put(
        '/admin/material/update/' + this.item.id + '/filename',
        data,
        response => {
          this.$message.success('操作成功');
          this.$emit('update:filename', {
            id: this.item.id,
            ...data
          });
          this.$emit('update:visible', false);
        },
        _ => {
          this.$message.error('操作失败');
        },
        false
      );
    }
  }
};
</script>
